//
//  MainViewController.swift
//  WeiBo001
//
//  Created by Zhanghong on 15/6/26.
//  Copyright © 2015年 HeiMa. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setValue(MainTabBar(), forKey: "tabBar")
        addChildViewControllers()
        
        let tab = tabBar as! MainTabBar
        tab.composeButton.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    func composeButtonClick(){
        print("点击了")
    }
    
    
    // 加载json文件中的数据，如果转换成功则通过json中的数据添加控制器，如果不成功则在catch异常处理中通过字符串添加控制器
    func addChildViewControllers(){
        let path = NSBundle.mainBundle().pathForResource("MainVcSetting.json", ofType: nil)!
        let data = NSData(contentsOfFile: path)!
        
        do{
            let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            for dict in array as! [[ NSString : NSString]] {
                loadChildController(dict["vcName"]! as String, title: dict["title"]! as String, imgName: dict["imageName"]! as String)
            }
            
        }catch{
            print(error)
            loadChildController("HomeTableViewController", title: "首页", imgName: "tabbar_home")
            loadChildController("MessageTableViewController", title: "消息", imgName:"tabbar_message_center")
            loadChildController("DiscoverTableViewController", title: "发现", imgName: "tabbar_discover")
            loadChildController("ProfileTableViewController", title: "我", imgName: "tabbar_discover")
        }
        
    }

    func loadChildController(vcName: String,title: String, imgName:String){
        tabBar.tintColor = UIColor.orangeColor()
        
        let namespace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String!
        let clsName = namespace + "." + vcName
        let cls : AnyClass = NSClassFromString(clsName)!
        
        let vc = cls.new() as! UITableViewController
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imgName)
        vc.tabBarItem.selectedImage = UIImage(named: imgName+"_highlighted")
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }

}
